package org.eredlab.g4.rif.util;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import net.sf.ehcache.search.Query;

import org.eredlab.g4.ccl.datastructure.Dto;
import org.eredlab.g4.ccl.datastructure.impl.BaseDto;
import org.eredlab.g4.ccl.util.G4Utils;

/**
 * 和Web层相关的实用工具类
 * 
 * @author 熊春,huangxy
 * @since 2008-09-22,2011-04-26 新增全局参数到缓存服务器
 */
public class WebUtils {
	/**
	 * 
	 * 
	 */
	private final static CacheManager cacheManager = new CacheManager();
	private final static Cache cache = cacheManager.getCache("et/g4/codes");
	/**
	 * 获取一个SessionContainer容器,如果为null则创建之
	 * 
	 * @param form
	 * @param obj
	 */
	public static SessionContainer getSessionContainer(HttpServletRequest request) {
		SessionContainer sessionContainer = (SessionContainer) request.getSession().getAttribute("SessionContainer");
		if (sessionContainer == null) {
			sessionContainer = new SessionContainer();
			HttpSession session = request.getSession(true);
			session.setAttribute("SessionContainer", sessionContainer);
		}
		return sessionContainer;
	}
	
	/**
	 * 获取一个SessionContainer容器,如果为null则创建之
	 * 
	 * @param form
	 * @param obj
	 */
	public static SessionContainer getSessionContainer(HttpSession session) {
		SessionContainer sessionContainer = (SessionContainer) session.getAttribute("SessionContainer");
		if (sessionContainer == null) {
			sessionContainer = new SessionContainer();
			session.setAttribute("SessionContainer", sessionContainer);
		}
		return sessionContainer;
	}

	/**
	 * 获取一个Session属性对象
	 * 
	 * @param request
	 * @param sessionName
	 * @return
	 */
	public static Object getSessionAttribute(HttpServletRequest request, String sessionKey) {
		Object objSessionAttribute = null;
		HttpSession session = request.getSession(false);
		if (session != null) {
			objSessionAttribute = session.getAttribute(sessionKey);
		}
		return objSessionAttribute;
	}

	/**
	 * 设置一个Session属性对象
	 * 
	 * @param request
	 * @param sessionName
	 * @return
	 */
	public static void setSessionAttribute(HttpServletRequest request, String sessionKey, Object objSessionAttribute) {
		HttpSession session = request.getSession();
		if (session != null)
			session.setAttribute(sessionKey, objSessionAttribute);
	}

	/**
	 * 移除Session对象属性值
	 * 
	 * @param request
	 * @param sessionName
	 * @return
	 */
	public static void removeSessionAttribute(HttpServletRequest request, String sessionKey) {
		HttpSession session = request.getSession();
		if (session != null)
			session.removeAttribute(sessionKey);
	}

	/**
	 * 将请求参数封装为Dto
	 * 
	 * @param request
	 * @return
	 */
	public static Dto getPraramsAsDto(HttpServletRequest request) {
		Dto dto = new BaseDto();
		Map map = request.getParameterMap();
		Iterator keyIterator = (Iterator) map.keySet().iterator();
		while (keyIterator.hasNext()) {
			String key = (String) keyIterator.next();
			String value = ((String[]) (map.get(key)))[0];
			dto.put(key, value);
		}
		//分页参数
		String start = request.getParameter("start");
		String limit = request.getParameter("limit");
		int startInt = 0;
		if (G4Utils.isNotEmpty(start)) {
		    startInt = Integer.parseInt(start);
		    if (G4Utils.isOracle()) {
		    	dto.put("start", startInt + 1);
			}else if (G4Utils.isMysql()) {
				dto.put("start", startInt);
			}else {
				dto.put("start", startInt);
			}
		}
		if (G4Utils.isNotEmpty(limit)) {
			int limitInt = Integer.parseInt(limit);
			if (G4Utils.isOracle()) {
				dto.put("end", limitInt + startInt);
			}else if (G4Utils.isMysql()) {
				dto.put("end", limitInt);
			}else {
				dto.put("end", limitInt);
			}
		}
		return dto;
	}

	/**
	 * 获取代码对照值
	 * 
	 * @param field
	 *            代码类别
	 * @param code
	 *            代码值
	 * @param request
	 * @return
	 */
	public static String getCodeDesc(String pField, String pCode, HttpServletRequest request) {
		//Element elment = cache.get(pField+pCode);
		//return elment==null?"":((BaseDto)elment.getObjectValue()).getAsString("codedesc");
		//List codeList = (List) request.getSession().getServletContext().getAttribute("EACODELIST");
		List codeList = getCodeListByField(pField,request);
		String codedesc = null;
		for (int i = 0; i < codeList.size(); i++) {
			Dto codeDto = (BaseDto) codeList.get(i);
			if(pCode.equalsIgnoreCase(codeDto.getAsString("code")))
				return codeDto.getAsString("codedesc");
		}
		return codedesc;
	}

	/**
	 * 根据代码类别获取代码表列表
	 * 
	 * @param codeType
	 * @param request
	 * @return
	 */
	public static List getCodeListByField(String pField, HttpServletRequest request) {
		//List codeList = (List) request.getSession().getServletContext().getAttribute("EACODELIST");
		//List lst = new ArrayList();
		//return cache.createQuery().includeKeys().includeValues().addCriteria(Query.KEY.ilike(pField+"*")).execute().all();
		Element element = cache.get(pField);
		if(element == null)
			return new ArrayList();
		else
			return ((Dto)element.getObjectValue()).getDefaultAList();
		/*for(int i=0;i<cache.getKeys().size();i++)
		{
			String key = (String) cache.getKeys().get(i);
			if(key.toLowerCase().startsWith(pField.toLowerCase()))
				lst.add(null);		
		}*/
		/*for (int i = 0; i < codeList.size(); i++) {
			Dto codeDto = (BaseDto) codeList.get(i);
			if (codeDto.getAsString("field").equalsIgnoreCase(pField)) {
				lst.add(codeDto);
			}
		}*/
		//return lst;
	}
	/**
	 * 设置全局参数值
	 */
	public static void putParamValue(Element element)
	{
		cache.put(element);
	}
	/**
	 * 获取全局参数值
	 * @param pParamKey 参数键名
	 * @return
	 */
	public static String getParamValue(String pParamKey, HttpServletRequest request){
		//String paramValue = "";
		Element elment = cache.get(pParamKey);
		return elment==null?"":elment.getObjectValue().toString();
		/*ServletContext context = request.getSession().getServletContext();
		if(G4Utils.isEmpty(context)){
			return "";
		}
		List paramList = (List) context.getAttribute("EAPARAMLIST");
		for (int i = 0; i < paramList.size(); i++) {
			Dto paramDto = (BaseDto) paramList.get(i);
			if (pParamKey.equals(paramDto.getAsString("paramkey"))){
				paramValue = paramDto.getAsString("paramvalue");
			}
		}*/
		//return paramValue;
	}
	/**
	 * 获取缓存对象
	 * @param pParamKey 参数键名
	 */
	public static Element getParamElement(String pParamKey)
	{
		return cache.get(pParamKey);
	}
	/**
	 * 获取全局参数
	 * 
	 * @return
	 */
	public static List getParamList(HttpServletRequest request) {
		ServletContext context = request.getSession().getServletContext();
		if (G4Utils.isEmpty(context)) {
			return new ArrayList();
		}
		return (List) context.getAttribute("EAPARAMLIST");
	}
}
